import { defineStore } from "pinia";
import $axios from "../utils/axios";

export const useMenuStore = defineStore("menu", {
    state: () => {
        return {
            menus: [],
            menutree: {},
            menus4me: [],
            menutree4me: [],
            ActivityTypeView: ["社区活动管理", "活动类型管理"],
            ActivityMenageView: ["社区活动管理", "活动管理"],
            ServiceTypeView: ["社区服务管理", "服务分类"],
            ServiceOrderView: ["社区服务管理", "订单管理"],
            HealthMenageView: ["健康管理", "健康档案"],
            HealthOrderView: ["健康管理", "订单管理"],
            UserMenageView: ["系统管理", "用户管理"],
            UserAuditView: ["系统管理", "用户审核"],
            WorkerMenageView: ["系统管理", "工作人员管理"],
            DoctorMenageView: ["系统管理", "医护人员管理"],
            MenuManage: ["助餐管理", "菜谱管理"],
            DiningFeedbackManage: ["助餐管理", "需求管理"],
            DiningFeedbackAdminView: ["助餐管理", "需求回复"],
            DiningImprovementView: ["助餐管理", "建议改进"],
            NewsManageView: ["系统管理", "新闻管理"],
            NewsCategoryView: ["系统管理", "新闻分类"],
            IndexView: ["系统管理", "首页概览"],
            currentpath: "ActivityMenageView",
            formPassenger: {
                roleId: -1,
            }
        }
    },
    getters: {
        getCrmbreadcrumbByPageName: (state) => {
            return state[state.currentpath] || ["首页"];
        },
    },
    actions: {
        async findPassenger(username) {
            const path = "/user/selectByUsername/" + username;
            const { data: res } = await $axios.get(path);
            if (res.code === 200) {
                this.formPassenger = res.result[0];
                console.log(this.formPassenger.roleId);
            }
        },
        async load4MeByLists() {
            try {
                const userStr = localStorage.getItem("user");
                const roleId = localStorage.getItem("roleId");
                
                if (!userStr || !roleId) {
                    console.error('用户未登录或角色ID不存在');
                    return;
                }
                
                const user = JSON.parse(userStr);
                console.log('当前用户:', user.username);
                console.log('当前角色:', roleId);
                
                this.menus4me = [];
                const path = "/sysFunction/selectByRid/" + roleId;
                const { data: res } = await $axios.get(path);
                
                if (res.code === 200) {
                    console.log('用户菜单:', res.result);
                    this.menus4me = res.result;
                    
                    // 检查菜单配置
                    this.menus4me.forEach(menu => {
                        if (!menu.path && menu.fId !== 0 && menu.fId !== 1) {
                            console.warn('发现路径为空的菜单项:', menu);
                        }
                    });
                    
                    // 构建菜单树
                    this.buildMenuTree4Me();
                    
                    // 输出菜单树结构
                    console.log('菜单树结构:', JSON.stringify(this.menutree4me, null, 2));
                } else {
                    console.error('加载菜单失败:', res.msg);
                }
            } catch (error) {
                console.error('加载菜单失败:', error);
            }
        },
        buildMenuTree4Me() {
            this.menutree4me = [];
            const root = this.menus4me.find((menu) => menu.fId === 0);
            this.fillChildren(root);
            this.menutree4me[0] = root;
        },
        getChildren4me(fId) {
            // if (this.menu4me) {
            // console.log(this.menus4me.filter((menu) => menu.fId === fId));
            return this.menus4me.filter((menu) => menu.fId === fId);
            // }
        },
        setCurrentpath(to) {
            this.currentpath = to.name;
        },
        getChildren(fId) {
            // if (this.menu4me) {
            return this.menus.filter((menu) => menu.fId === fId);
            // }
        },
        /**
         * 填充root节点的孩子节点
         * @param {*} root
         */
        fillChildren(root) {
            if (root == null) return;
            // 从menus中寻找root节点的所有孩子节点
            root.children = [];
            for (let i = 0; i < this.menus.length; i++) {
                if (this.menus[i].fId === root.id) {
                    root.children.push(this.menus[i]);
                }
            }
            for (
                let i = 0;
                root != null && root.children != null && i < root.children.length;
                i++
            ) {
                this.fillChildren(root.children[i]);
            }
        },
        /**
        * 转换List到Tree
        */
        buildMenuTree() {
            this.menutree = [];
            const root = this.menus.find((menu) => menu.fId === 0);
            this.fillChildren(root);
            this.menutree[0] = root;
            console.log(this.menutree);
        },
        async loadAllByLists() {
            this.menus = [];
            const path = "/sysFunction/selectAll";
            const { data: res } = await $axios.get(path);
            if (res.code === 200) {
                this.menus = res.data;
                this.buildMenuTree();
            }
            console.log(this.menus);
        },
    }
})